/**
 * Created by Administrator on 2017/3/14.
 */
var Breadcrumb = require('../../../src/libs/breadcrumb');
var InvestAction = require('../complex/investAction');
var Progress = require('../../../src/libs/progress');
var Tooltip = require('../../../src/libs/tooltip');
var InputNumber = require('../../../src/libs/input-number');
var Tabs = require('../../../src/libs/tabs');
var TabItem = Tabs.TabItem;
var Pagination = require('../../../src/libs/pagination');
var GuaranteeList = {
    "营业执照": "icon-yyzz",
    "融资方经营场所实地认证": "icon-rzfjrcsdzz",
    "税务登记证": "icon-swdjz",
    "账务表已审计": "icon-zwbysj",
    "组织机构代码证": "icon-zjjgdmz",
    "融资方从业年限": "icon-rzfcynx",
    "基本账户开户许可": "icon-jbzfkfxk",
    "融资方已在银行授信": "icon-rzfyzyhsx",
    "融资方成立年限": "icon-rzfclnx",
    "人行征信-无不良信用记录": "icon-rhzx",
    "授信方式-抵押": "icon-sxfsdy",
    "授信方式-质押": "icon-sxfszy",
    "融资方经营情况调查": "icon-rzfjyqkdc"
}

var InvestRecord = React.createClass({
    getInitialState:function () {
        return{
            InvestmentRecordVal: PageDM.InvestmentRecord.value,
            pageVal: PageDM.pagination.value
        }
    },
    pageClick:function (v) {
        PageDM.pagination.setValue({curPage:v});
        PageDM.pagination.onClick(v);
    },
    render:function () {
        var _this  = this;
        return (
            <div>
                <table className="table-3 table-even">
                    <thead>
                    <tr>
                        <th>投资用户</th>
                        <th>投资金额</th>
                        <th>是否投资成功</th>
                        <th>投资时间</th>
                    </tr>
                    </thead>
                    <tbody ref="investmentRecordTb">
                    {
                        _this.state.InvestmentRecordVal.length > 0 ? (_this.state.InvestmentRecordVal.map(function(item,index){
                            var PayAmount = UFormatter.formatMoney(Number(item.PayAmount),2);
                            return (
                                <tr>
                                    <td>{item.PayUserName}</td>
                                    <td>{PayAmount}</td>
                                    <td><span className="iconfont icon-success"></span></td>
                                    <td>{item.PayTime}</td>
                                </tr>
                            )
                        })):(<tr><td colSpan="4">暂无记录</td></tr>)
                    }
                    </tbody>
                </table>
                <Pagination  pageVal={_this.state.pageVal} onClick={this.pageClick}></Pagination>
            </div>
        )
    }

});
var Root = React.createClass({
    getInitialState: function () {
        return {
            pageVal: PageDM.pagination.value,
            ProDetailVal: PageDM.ProDetail.value,
            InvestmentRecordVal: PageDM.InvestmentRecord.value,
            PartsCount:PageDM.ProDetail.value.FinanceDetail.EachPartAmount * PageDM.ProDetail.value.FinanceDetail.MinInvestPartsCount
        }
    },

    componentDidMount: function(){
        var _this = this;

        UEventHub.on(PageDM.ProDetail.dmbind + UI_EVENT_CONST.SET_UDM_VALUE_EVENT, function(v){
            _this.setState({
                ProDetailVal: v,
                PartsCount:PageDM.ProDetail.value.FinanceDetail.EachPartAmount * PageDM.ProDetail.value.FinanceDetail.MinInvestPartsCount
            });
        });
        UEventHub.on(PageDM.InvestmentRecord.dmbind + UI_EVENT_CONST.SET_UDM_VALUE_EVENT, function(v){
            _this.refs.InvestRecord.setState({
                InvestmentRecordVal: v
            });
        });
        UEventHub.on(PageDM.pagination.dmbind + UI_EVENT_CONST.SET_UDM_VALUE_EVENT, function(v){
            _this.refs.InvestRecord.setState({
                pageVal: v
            });
        });
        UEventHub.on('countOver',function (v) {
            _this.setState({
                ProDetailVal:{
                    FinanceDetail:v
                }
            })
        });
        UEventHub.emit("pageLoad","hello world!");
    },
    investSumChangeHandler: function(v){
        var FinanceDetail = PageDM.ProDetail.value.FinanceDetail;
        var val = parseInt(v / FinanceDetail.AppendBuyAmount) * FinanceDetail.AppendBuyAmount;

        var money = UMath.Earnings(val, this.state.ProDetailVal.FinanceDetail.Interest, this.state.ProDetailVal.FinanceDetail.Duration, PageDM.days.value);
        money = UFormatter.formatMoney(money);
        this.refs['expectedReturn'].innerHTML = money;
        window.PageDM.ProDetail.value.FinanceDetail.PartsCount = val;
        this.state.PartsCount = val;
        this.refs.inputnumber.setValue(val);
    },
    tabsCallBack: function(index){
        this.defaultActiveKey = index;
    },
    defaultActiveKey:0,
    render: function () {
        var _this = this, FinanceDetail = _this.state.ProDetailVal.FinanceDetail;
        //投资动作Props
        var actionData = {
            minFlag:_this.state.ProDetailVal.FinanceDetail.minFlag?_this.state.ProDetailVal.FinanceDetail.minFlag:false,
            flag:{
                login:_this.state.ProDetailVal.FinanceDetail.login,
                loginUrl:_this.state.ProDetailVal.FinanceDetail.loginUrl,
                confirmUrl:_this.state.ProDetailVal.FinanceDetail.confirmUrl,
                ProjectStatus:_this.state.ProDetailVal.FinanceDetail.ProjectStatus,
                JMBeginTime:_this.state.ProDetailVal.FinanceDetail.JMBeginTime,
                ProjectBeginTime:_this.state.ProDetailVal.FinanceDetail.ProjectBeginTime,
                MinInvestPartsCount:_this.state.ProDetailVal.FinanceDetail.MinInvestPartsCount,
                MaxInvestPartsCount:_this.state.ProDetailVal.FinanceDetail.MaxInvestPartsCount,
                EachPartAmount:_this.state.ProDetailVal.FinanceDetail.EachPartAmount
            }
        };
        //数字格式化
        var _start = UFormatter.formatMoney(FinanceDetail.MinInvestPartsCount * FinanceDetail.EachPartAmount),//投资说明，起投金额
            _each = UFormatter.formatMoney(Number(FinanceDetail.AppendBuyAmount)),//投资说明，递增金额
            TotalAmount = UFormatter.formatMoney(Number(FinanceDetail.TotalAmount),2),//本金
            _minPart = UFormatter.formatMoney(FinanceDetail.EachPartAmount*FinanceDetail.MinInvestPartsCount),
            _earnings = UMath.Earnings(_this.state.PartsCount, _this.state.ProDetailVal.FinanceDetail.Interest, _this.state.ProDetailVal.FinanceDetail.Duration, PageDM.days.value),
            _expect = UMath.Earnings(_this.state.ProDetailVal.FinanceDetail.TotalAmount, _this.state.ProDetailVal.FinanceDetail.Interest, _this.state.ProDetailVal.FinanceDetail.Duration, PageDM.days.value);
        _expect = UFormatter.formatMoney(_expect,2);//项目详情-预期收益
        _earnings = UFormatter.formatMoney(_earnings,2);//预期收益
        //未登录剩余金额
        var unLoginRemain = UFormatter.formatMoney(FinanceDetail.RemainPartsCount * FinanceDetail.EachPartAmount);
        //已登录
        var loginMax = FinanceDetail.MaxInvestPartsCount * FinanceDetail.EachPartAmount,
            MinInvest = FinanceDetail.MinInvestPartsCount * FinanceDetail.EachPartAmount;
            // console.log('用户在该项目的剩余可投金额: ' + loginMax);
            // console.log('项目最小投资金额: ' + MinInvest);

        /*活动标志*/
        var Aflag_Icon = FinanceDetail.Aflag_Icon;
        var arr_aflag, resetAflag = [];
        if(Aflag_Icon){
            arr_aflag = Aflag_Icon.split(',');
            for(var i = 0;i < arr_aflag.length;i++){
                resetAflag.push(arr_aflag[i].split('|'));
            }
        }

        //尾单金额
        var _value = _this.state.PartsCount;
        if(loginMax < MinInvest){ //个人剩余能投金额小于起投金额
            if(FinanceDetail.RemainPartsCount <= loginMax){   //项目剩余金额小于个人剩余能投金额
                _value = FinanceDetail.RemainPartsCount * FinanceDetail.EachPartAmount;
            }else if(FinanceDetail.RemainPartsCount > loginMax) {//项目剩余金额小于个人剩余能投金额
                _value = 0;
            }
        }
        _earnings = UMath.Earnings(_value, _this.state.ProDetailVal.FinanceDetail.Interest, _this.state.ProDetailVal.FinanceDetail.Duration, PageDM.days.value);
        _earnings = UFormatter.formatMoney(_earnings,2);//预期收益
        return (
            <div>
                <div className="container">
                    <Breadcrumb	separator='>' >
                        <Breadcrumb.Item href={PageDM.URL.home}>首页</Breadcrumb.Item>
                        <Breadcrumb.Item href={PageDM.URL.investList}>我要投资</Breadcrumb.Item>
                        <Breadcrumb.Item>项目详情</Breadcrumb.Item>
                    </Breadcrumb>

                    <div className="project-detail" ref="projectDetail">
                        <h1 className="title">
                            {FinanceDetail.ProjectName?FinanceDetail.ProjectName:""}
                            {FinanceDetail.IsExclusive?
                                (FinanceDetail.IsExclusivePublic?
                                    <Tooltip className="bg-icon tag tag-zhuang" title="专属项目，需输入项目专属识别码才可投标"></Tooltip> :
                                    <span className="bg-icon tag tag-zhuang"></span>)
                                :""
                            }
                            {resetAflag ?
                                resetAflag.map(function(v,j){
                                    var _src = "../content/images/ActImage/"+v[0];
                                    if(v[1]){
                                        return <Tooltip title={v[1]} className="tag"><img src={_src}/></Tooltip>
                                    }else{
                                        return <span className="tag"><img src={_src}/></span>
                                    }
                                }) : ""
                            }
                        </h1>
                        <div className="row clearfix">
                            <div className="f-left col-left">
                                <div className="detail-info clearfix">
                                    <ul>
                                        <li>
                                            {_this.state.ProDetailVal.FinanceDetail.Interest?(<p className="fc-main"><b>{_this.state.ProDetailVal.FinanceDetail.Interest}</b>%</p>):""}
                                            {_this.state.ProDetailVal.FinanceDetail.Interest?(<p className="fc-light">预期年化收益率</p>):""}
                                        </li>
                                        <li>
                                            {_this.state.ProDetailVal.FinanceDetail.Duration?(<p><b>{_this.state.ProDetailVal.FinanceDetail.Duration}</b>天</p>):""}
                                            {_this.state.ProDetailVal.FinanceDetail.Duration?(<p className="fc-light">项目期限</p>):""}
                                        </li>
                                        <li>
                                            {_this.state.ProDetailVal.FinanceDetail.TotalAmount?(<p><b>{_this.state.ProDetailVal.FinanceDetail.TotalAmount<10000?_this.state.ProDetailVal.FinanceDetail.TotalAmount:(_this.state.ProDetailVal.FinanceDetail.TotalAmount/10000).toFixed(2)}</b>{_this.state.ProDetailVal.FinanceDetail.TotalAmount<10000?"元":"万元"}</p>):""}
                                            {_this.state.ProDetailVal.FinanceDetail.TotalAmount?(<p className="fc-light">项目规模</p>):""}
                                        </li>
                                    </ul>
                                </div>
                                <div className="detail-progress clearfix">
                                    <label>募集进度：</label>
                                    <Progress className="progress" type="line" percent={_this.state.ProDetailVal.FinanceDetail.Progress}></Progress>
                                    <p className="f-left">见证银行：<img className="detail-logo" src="../content/images/logo2.jpg" alt=""/> {_this.state.ProDetailVal.FinanceDetail.BankName}</p>
                                </div>
                            </div>
                            <div className="f-right detail-other">
                                <p>项目起息日：{_this.state.ProDetailVal.FinanceDetail.ValueBegin}</p>
                                <p>项目到期日：{_this.state.ProDetailVal.FinanceDetail.RepayBegin}</p>
                                <p>还款方式：到期一次性还本付息</p>
                                <p>投资说明：{_start}元起投，递增金额{_each}元</p>
                            </div>
                        </div>
                        <div className="line"><b className="iconfont icon-ring"></b> <i className="iconfont icon-ring"></i></div>
                        <div className="row-bid clearfix">
                            <div className="f-left bid-money clearfix">
                                <div className="money f-left"><label>投资金额：</label>
                                    <InputNumber step={_this.state.ProDetailVal.FinanceDetail.AppendBuyAmount}
                                                 max={_this.state.ProDetailVal.FinanceDetail.EachPartAmount*_this.state.ProDetailVal.FinanceDetail.MaxInvestPartsCount}
                                                 min={_this.state.ProDetailVal.FinanceDetail.EachPartAmount*_this.state.ProDetailVal.FinanceDetail.MinInvestPartsCount}
                                                 value={_value}
                                                 ref="inputnumber"
                                                 disabled={(FinanceDetail.ProjectStatus>2 || FinanceDetail.RemainPartsCount < FinanceDetail.MinInvestPartsCount || loginMax < MinInvest)? true:false}
                                                 onChange={this.investSumChangeHandler.bind(this)}/>
                                    <div className="unit">元</div>
                                    <div className="tips fc-main">
                                        {_this.state.ProDetailVal.FinanceDetail.ProjectStatus > 2?"":( !actionData.flag.login ?
                                            <p>项目剩余可投金额为{unLoginRemain}元</p> :
                                            (loginMax < MinInvest) ?
                                                (FinanceDetail.RemainPartsCount <= loginMax ?
                                                    <p>您在此项目的剩余可投金额为{UFormatter.formatMoney(FinanceDetail.RemainPartsCount * FinanceDetail.EachPartAmount)}元</p> :
                                                    <p>您在此项目的剩余可投金额不足，请选择其他项目</p>
                                                ) :
                                                <p>您在此项目的剩余可投金额为{UFormatter.formatMoney(loginMax)}元</p>
                                        )}
                                    </div>
                                </div>
                                <div className="income f-left">预期收益：<b className="fc-main" ref="expectedReturn">{_earnings}</b> 元</div>
                            </div>
                            <div className="f-right bid">
                                <InvestAction data={actionData}/>
                            </div>
                        </div>
                        <span className="angle angle-top"></span>
                        <span className="angle angle-bottom"></span>
                    </div>

                    <div className="project-info">
                        <Tabs defaultActiveKey={_this.defaultActiveKey} callback={_this.tabsCallBack.bind(_this)}>
                            <TabItem tab="项目详情">
                                <div ref="projectDetailTb">
                                    <div className="title"><b></b>项目用途<b></b></div>
                                    <div className="content">
                                        <pre>{_this.state.ProDetailVal.ProjectContent.Content}</pre>
                                    </div>
                                    <div className="title"><b></b>银行见证信息<b></b></div>
                                    <div className="content bank-info">
                                        <ul className="clearfix">
                                            {
                                                _this.state.ProDetailVal.GuaranteeList.map(function(item,index){
                                                    return (<li><i className={GuaranteeList[item.Title]}></i>{item.Title}</li>);
                                                })
                                            }
                                        </ul>
                                    </div>
                                    <div className="title"><b></b>预期项目收益<b></b></div>
                                    <div className="content">
                                        <table className="table-1">
                                            <tbody>
                                                <tr>
                                                    <td></td>
                                                    <td className="fc-link">金额</td>
                                                    <td className="fc-link">还款时间</td>
                                                </tr>
                                                <tr>
                                                    <td className="fc-light">预期收益</td>
                                                    <td className="fc-light"><b className="fc-main">{_expect}</b> 元</td>
                                                    <td className="fc-light">{_this.state.ProDetailVal.FinanceDetail.RepayBegin}</td>
                                                </tr>
                                                <tr>
                                                    <td className="fc-light">本金</td>
                                                    <td className="fc-light"><b className="fc-main">{TotalAmount}</b> 元</td>
                                                    <td className="fc-light">{_this.state.ProDetailVal.FinanceDetail.RepayBegin}</td>
                                                </tr>
                                            </tbody>

                                        </table>
                                        <div className="tips fc-light">免责声明：项目预期收益仅供参考，具体以实际收益为准</div>
                                    </div>
                                    <div className="title"><b></b>重要说明及风险提示<b></b></div>
                                    <div className="content">
                                        <p>
                                            <b>本项目非银行存款、银行理财计划或银行代销产品，请认真阅读本重要说明及风险提示。在投资本项目前，投资人应确保自己完全明白该项投资的性质和所涉及的风险，详细了解和审慎评估该项目的资金投资方向、风险类型及预期收益等基本情况，在慎重考虑后自行决定购买与自身风险承受能力和资产管理需求匹配的产品。</b>
                                        </p>
                                        <p>1.本项目为网络投融资产品，募集资金主要用于融资人（借款人）的借款需要，如出现前述融资人（借款人）未按时足额支付本息等不利情况，则本项目将有收益为零甚至本金损失的可能。本平台不对融资人归还融资本息提供任何形式的担保。</p>
                                        <p>2. 浙江新昌农村商业银行股份有限公司作为项目见证机构，仅对融资(借款)方在本平台上的披露信息进行形式审核，不对其现在及将来的资信状况、还款能力进行任何审核或评估；平台委托第三方支付机构进行资金监管及本金、利息清算。</p>
                                        <p>3. 除本《项目说明书》中明确规定的收益及收益分配方式外，任何预计收益、测算收益或类似表述均属不具有法律约束力的用语，不代表投资人可能获得的实际收益，亦不构成本平台和项目见证机构对本项目的任何收益承诺。投资人所能获得的最终收益以本《项目说明书》所规定形式实际支付的款项为准， 且不超过根据《项目说明书》预期投资收益率计算所得的金额。</p>
                                        <p>4. 本平台有权依法对本《项目说明书》进行解释。</p>
                                    </div>
                                </div>
                            </TabItem>
                            <TabItem tab="项目说明书">
                                <table className="table-2 table-even" ref="projectBookTb">
                                    <tbody ref="proBook">
                                    <tr>
                                        <th>项目名称：</th>
                                        <td>{_this.state.ProDetailVal.FinanceDetail.ProjectName}</td>
                                    </tr>
                                    <tr>
                                        <th>项目期限：</th>
                                        <td><span className="fc-main">{_this.state.ProDetailVal.FinanceDetail.Duration}</span> 天</td>
                                    </tr>
                                    <tr>
                                        <th>投资（借出）及收益币种：</th>
                                        <td>人民币</td>
                                    </tr>
                                    <tr>
                                        <th>产品类型：</th>
                                        <td>固定期限网络投融资产品</td>
                                    </tr>
                                    <tr>
                                        <th>预期年化收益率：</th>
                                        <td><span className="fc-main">{_this.state.ProDetailVal.FinanceDetail.Interest}</span>%</td>
                                    </tr>
                                    <tr>
                                        <th>融资（总借入）金额：</th>
                                        <td><span className="fc-main">{TotalAmount}</span>元</td>
                                    </tr>
                                    <tr>
                                        <th>募集期：</th>
                                        <td>{_this.state.ProDetailVal.FinanceDetail.FormatProjectBeginTime}～{_this.state.ProDetailVal.FinanceDetail.FormatJMBeginTime}</td>
                                    </tr>
                                    <tr>
                                        <th>项目起息日：</th>
                                        <td>募集结束，资金划转至融资人账户后的首个工作日。资金在起息日前不计算利息</td>
                                    </tr>
                                    <tr>
                                        <th>项目到期日：</th>
                                        <td>{_this.state.ProDetailVal.FinanceDetail.RepayBegin}，投资资金在项目到期日当天不计算利息</td>
                                    </tr>
                                    <tr>
                                        <th>资金到账日：</th>
                                        <td>到期日后1-3个工作日</td>
                                    </tr>
                                    <tr>
                                        <th>最小投资（借款）单位：</th>
                                        <td><span className="fc-main">{_minPart}</span>元，并须以最小投资单位的整数倍递增</td>
                                    </tr>
                                    <tr>
                                        <th>超募：</th>
                                        <td>如多个投资人在募集期间进行的投资导致项目实际募集资金超过项目融资规模（即产生超募），平台将根据投资人的投资时间
                                            顺序将顺序在后的投资资金/部份投资资金（即超募资金）于所投项目募集期结束日的T+1日（均为工作日，非工作日将延后至
                                            下一工作日），通过第三方支付机构向投资人指定回款账户退款
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>节假日：</th>
                                        <td>本项目在中国法定节假日期间亦可投标</td>
                                    </tr>
                                    <tr>
                                        <th>税款：</th>
                                        <td>投资收益的应纳税款由投资人自行申报及缴纳</td>
                                    </tr>
                                    <tr>
                                        <th>收益计算方法：</th>
                                        <td>期末收益=投资本金 x 预期年化收益 x 产品存续天数/{PageDM.days.value}</td>
                                    </tr>
                                    <tr>
                                        <th>提前终止权：</th>
                                        <td>会员无权提前终止该产品或要求提前收取本金或收益</td>
                                    </tr>
                                    <tr>
                                        <th>其他规定：</th>
                                        <td>到期日至实际到账之间，客户资金（含本金、收益、罚息等）不计利息</td>
                                    </tr>
                                    <tr>
                                        <th>见证机构：</th>
                                        <td>浙江新昌农村商业银行股份有限公司</td>
                                    </tr>
                                    <tr>
                                        <th>支付清算机构：</th>
                                        <td>中金支付有限公司</td>
                                    </tr>
                                    <tr>
                                        <th>工作日：</th>
                                        <td>浙江新昌农村商业银行股份有限公司对公业务工作日</td>
                                    </tr>
                                    </tbody>
                                </table>
                            </TabItem>
                            <TabItem tab="成交记录">
                                <InvestRecord ref="InvestRecord" />
                            </TabItem>
                        </Tabs>
                    </div>
                </div>

            </div>
        )
    }
});
ReactDOM.render(<Root/>, document.getElementById('giraffe'));